<?php

/**
 * класс для работы с таблицей файлов тендеров
 *
 * @author kingop
 */
class DatabaseObject_TendersFiles extends DatabaseObject {

    public function __construct($db) {
        parent::__construct($db, 'tenders_files', 'id');

        // далее перечислим все поля таблицы
        $this->add('filename');
        $this->add('name');
        $this->add('idTender');
    }

    public static function GetTenderFiles($db, $id) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, '*');
        $select->where('idTender = ?', $id);

        $data = $db->fetchAll($select);

        $tFiles = self::BuildMultiple($db, __CLASS__, $data);

        return $tFiles;
    }

    public static function DeleteTenderFileID($db, $id) {
        $query = sprintf("delete from %s where id = %d", 'tenders_files', $id);

        $db->query($query);

        return true;
    }

    public static function DeleteTenderFiles($db, $id) {
        $query = sprintf("delete from %s where idTender = %d", 'tenders_files', $id);

        $db->query($query);

        return true;
    }

    public static function UploadFile($db, $idTender, $file) {

        $tFile = new DatabaseObject_TendersFiles($db);
        $tFile->name = $file;
        $tFile->filename = 'tmp';
        $tFile->idTender = $idTender;
        $tFile->save();

        $temp = self::GetUploadDirectory() . '/' . $file;
        $tFile->filename = $tFile->getId() . '-' . time() . $file;
        $tFile->save();
        if (rename($temp, self::GetUploadDirectory() . '/' . $tFile->filename)) {
            return true;
        }

        return false;
    }

    public static function GetUploadDirectory() {
        return Zend_Registry::get('config')->paths->data . "/uploaded-files/docs";
    }

    private static function _GetBaseQuery($db, $options) {
        // инициализация настроек
        $defaults = array();

        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }

        // создание запроса на получение
        $select = $db->select();
        $select->from(array('p' => 'tenders_files'), array());

        return $select;
    }

}

?>
